package com.javaweb.dao.impl;

import com.javaweb.dao.TagDao;
import com.javaweb.model.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class TagDaoImpl implements TagDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Tag tag) {
        String sql = "INSERT INTO tb_tag (name, create_time) VALUES (?, ?)";
        int result = jdbcTemplate.update(sql, tag.getName(), tag.getCreateTime());
        return result == 1 ? 1 : 0;
    }

    @Override
    public int insertArticleTag(Integer articleId, Integer[] tags) {
        String sql = "INSERT INTO tb_article_tag (article_id, tag_id) VALUES (?, ?)";
        int successCount = 0;

        for (Integer tagId : tags) {
            int result = jdbcTemplate.update(sql, articleId, tagId);
            if (result == 1) {
                successCount++;
            }
        }

        return successCount == tags.length ? 1 : 0;
    }
}
